<?php
// +----------------------------------------------------------------------
// | Description: 用户 银行卡
// +----------------------------------------------------------------------
// | Author: linchuangbin <linchuangbin@honraytech.com>
// +----------------------------------------------------------------------

namespace app\v2\model;

use think\Db;

use think\Model;
use app\v2\model\UserInfo;
class UserBankCard extends Model 
{	

    protected $name = 'user_bank_card';
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $autoWriteTimestamp = 'datetime';
    /**
     * 通过uid修改用户资料
     * @author   yhq <934797303@qq.com>
     * @DateTime 2017-09-11T15:13:28+0800
     * @param    [type]                   $param [description]
     * @param    [type]                   $uid   [description]
     * @return   [type]                          [description]
     */
    public function updateDataByUId($param, $uid)
    {
        $res = $this->allowField(true)->save($param, ['uid' => $uid]);
        if(false!==$res){
            return true;
        }
        $this->error = '资料保存失败';
        return false;
    }


    /**
     * 修改 银行卡包内容
     * @author  llj <just05075@foxmail.com>
     * @date(2017年11月11日15:12:11)
     */
    public function modifyBankCardPackage($data){

        $thisBankCardNumberExist = $this->where(array('bank_card_number'=>$data['bank_card_number']))->field('bank_card_number,status')->find();

        $userBankCardCounts = $this->where(array('uid'=>$data['uid']))->count();
         // echo $userBankCardCounts;die;

        //设置默认银行卡时,防止出现没有默认银行卡的情况
        $this->defaultBankCardSafe($data);

        $this->startTrans();

        if($data['is_default'] && $userBankCardCounts){

            $save1['is_default'] = 0;
            $res = $this->allowField(true)->save($save1,['uid'=>$data['uid']]);
            if(!$res) {
                $this->error = '更新银行卡信息失败 -1000';
                return false;
            }

        }

        if($thisBankCardNumberExist){//已经存在该卡号的银行卡，只作更新
            if($thisBankCardNumberExist['status'])
            {
                $this->error = '该卡已被绑定';
                return false;
            }
            $res = $this->allowField(false)->save($data,['bank_card_number'=>$data['bank_card_number']]);
            if(!$res){
                $this->error = '更新银行卡失败 -1001';
                return false;
            }
            
        }else{//添加该卡号的银行卡

            // echo json_encode($data);die;
            // echo 123;die;
            $res = $this->create($data);
            if(!$res) {
                $this->error = '添加银行卡失败 -1002';
                return false;
            }
        }

        $this->commit();//重要,不许删除
        $this->error = 'success';
        return true;
    }

    /**
     * 设置默认银行卡时,防止出现没有默认银行卡的情况
     * @author  llj <just05075@foxmail.com>
     * @date(2017年11月11日15:12:11)
     */
    private function defaultBankCardSafe(&$data){

        $userDefalutBankCards = $this->where(array('uid'=>$data['uid'],'is_default'=>1))->column('bank_card_number');//['6212264100008604552']
        $userDefalutBankCardCounts = count($userDefalutBankCards);
        // echo json_encode($userDefalutBankCardCounts);die;
        
        $userBankCardCounts = $this->where(array('uid'=>$data['uid']))->count();

        if($data['is_default']){//设置该卡为默认时，请将该用户自己的其他卡默认状态都取消

        
        }else{//设置该卡为非默认时，有两种情况：

            //情况①；当前绑定操作为=》新增用户的第一张卡，必须强制为默认
            if($userDefalutBankCardCounts == 0){
                $data['is_default'] = 1;
            }

            //情况②：当前绑定的卡，与用户唯一存在的卡号相同（可能会更新电话号码），也必须强制为默认
            if($userDefalutBankCardCounts == 1 && in_array($data['bank_card_number'],$userDefalutBankCards) ){
                $data['is_default'] = 1;
            }
            
        }

        // dump($thisBankCardNumberExist);die;
        // echo json_encode($data);die;
        // 
    }

    /**
     * 设置默认银行卡
     * @author  llj <just05075@foxmail.com>
     * @date(2017年11月11日17:33:26)
     */
    
    public function setDefaultBankCard($data){

        //设置默认银行卡时,防止出现没有默认银行卡的情况
        $this->defaultBankCardSafe($data);

        $userBankCards = $this->where(array('uid'=>$data['uid']))->column('bank_card_number');//['6212264100008604552']

        if( !in_array($data['bank_card_number'],$userBankCards)){
            $this->error = '银行卡号不存在 -2002';
            return false;
        }
        
        // echo json_encode($userBankCards);die;
        $userBankCardCounts = count($userBankCards);
        // echo $userBankCardCounts;die;
        $this->startTrans();

        if($data['is_default'] && $userBankCardCounts){

            $save1['is_default'] = 0;
            $res = $this->allowField(true)->save($save1,['uid'=>$data['uid']]);
            // echo $this->getLastSql();die;
            if(!$res) {
                $this->error = '更新银行卡信息失败 -2000';
                return false;
            }

        }
        $save1['is_default'] = $data['is_default'];
        $res = $this->allowField(false)->save($save1,['bank_card_number'=>$data['bank_card_number']]);
        if(!$res){
            $this->error = '设置默认银行卡 失败 -2001';
            return false;
        }

        $this->error = 'success';
        $this->commit();//重要,不许删除
        return true;
    }
    /**
     * [getCardValue 获取字段]
     * @param  array  $where [description]
     * @param  string $value [description]
     * @param  string $order [description]
     * @return [type]        [description]
     */
    public function getCardValue($where = [], $value = 'id', $order = 'id')
    {
        return $this->where($where)->order($order)->value($value);
    }
    /**
     * [getCard 获取一条信息]
     * @param  array  $where [description]
     * @param  string $field [description]
     * @return [type]        [description]
     */
    public function getCard($where = [], $field = '*')
    {
        return $this->where($where)->field($field)->find();
    }
    /**
     * [saveParam 保存数据]
     * @param  array  $param [description]
     * @param  array  $where [description]
     * @return [type]        [description]
     */
    public function saveParam($param = [], $where = [])
    {
        $this->startTrans();
        try {
            $this->allowField(true)->save($param, $where);
            $data = $this->where($where)->field('uid,id_card,bank_card_number,name')->find();
            $datas['id_card'] = $data['id_card'];
            $datas['bank_card_number'] = $data['bank_card_number'];
            $datas['name'] = $data['name'];
            (new UserInfo)->allowField(true)->save($datas,['uid'=>$data['uid']]);
            $this->commit();
            return ture;
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
    }
    /**
     * [getDataList 获取银行卡列表]
     * @return [type] [description]
     */
    public function getDataList($where = [],$field = '*')
    {
        return $this->field($field)->where($where)->select();
    }

    /**
     * [checkBank 检查银行卡信息]
     * @param  string $id  [description]
     * @param  string $uid [description]
     * @return [type]      [description]
     */
    public function checkBank($id = '', $uid ='')
    {
        if(!$id)
        {
            $this->error = '请选择银行卡';
            return false;
        }
        $cardInfo = $this->getCard(['id' => $id],'bank_card_number,uid,name,bind_mob,id_card,user_nm');
        if(!$cardInfo || ($cardInfo['uid'] != $uid))
        {
            $this->error = '请确定银行卡信息正确';
            return false;   
        }
        return $cardInfo;

    }


}